package ChatNI;

import Controller.ChatController;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

import ourMessage.*;

/**
 *
 * @author Ridiss
 */
public class Receiver implements Runnable{

        private DatagramSocket socket;
        private Thread t;
        private ChatNI chatnet;
        
        private int id=0;
        
    /**
     *
     */
    public Receiver() {
                
            try {
                this.socket = new DatagramSocket(2014);
                t = new Thread(this, "Receiver Thread");
                t.start(); // Start the thread
               
           }
        catch(SocketException sE) {
        } 
        catch(NullPointerException e){
            
        }     
          
        }

        @Override
        public void run() {
                // TODO Auto-generated method stub
                 byte[] buffer = new byte[512];
                   
                   while(!(socket.isClosed())) {
                
                    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                    try {
                        socket.receive(packet);
                        chatnet=new ChatNI();
                         Message m = Message.fromArray(packet.getData());
                        
                        if(!m.getlogin().equals(ChatController.getLocalUsername1()) ){
                           
                         m.setlogin(m.getlogin()+"@"+packet.getAddress().getHostAddress());
                        
                            chatnet.Notifmsgrecu(m);
                        }   
                        
                    }   
                    catch(IOException iE) {
                    } catch (ClassNotFoundException ex) {
                         Logger.getLogger(Receiver.class.getName()).log(Level.SEVERE, null, ex);
                     }
                } 
        }

    /**
     *
     */
    public void closeReceiveSocket() {
                
                try {
                    socket.close();
                }
                catch(Exception e) {
                        
                }
            }

}
